package org.autumn.review.thread;


import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;

/**
 * Multi Thread Coordination
 */
@Slf4j
public class MultiThreadCoordination {
    static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        concurrentProblemResolve();
    }

    /**
     * test concurrent problem
     *
     * @throws InterruptedException
     */
    private static void concurrentProblem() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                count++;
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                // getstatic
                // iconst_1
                // isub
                // putstatic #13
                // count-- byte class
                // not atomic
                count--;
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        log.info("count -> {}", count);

    }


    private static void concurrentProblemResolve() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                synchronized (MultiThreadCoordination.class){
                    count++;
                }
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                // getstatic
                // iconst_1
                // isub
                // putstatic #13
                // count-- byte class
                // not atomic
                synchronized (MultiThreadCoordination.class){
                    count--;
                }
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.info("count -> {}", count);

    }
}
